package com.itcast.bulls.stock.deal.service;

import com.itcast.bulls.stock.common.encrypt.EncryptUtil;
import com.itcast.bulls.stock.common.exception.ComponentException;
import com.itcast.bulls.stock.common.utils.GlobalConstants;
import com.itcast.bulls.stock.deal.dao.biz.IStockUserDao;
import com.itcast.bulls.stock.deal.dao.biz.ITradeAccountDao;
import com.itcast.bulls.stock.deal.service.user.ITradeUserService;
import com.itcast.bulls.stock.entity.user.TradeAccount;
import com.itcast.bulls.stock.entity.user.TradeUser;
import com.itcast.bulls.stock.struct.grpc.trade.*;
import io.grpc.stub.StreamObserver;
import lombok.extern.log4j.Log4j2;
import net.devh.boot.grpc.server.service.GrpcService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;

@GrpcService
@Log4j2
public class GrpcStockUserService extends StockUserServiceGrpc.StockUserServiceImplBase {

    @Autowired
    private IStockUserDao stockUserDao;

    //交易账号
    @Autowired
    private ITradeAccountDao tradeAccountDao;


    @Autowired
    private ITradeUserService tradeUserService;


    @Override
    public void userLogin(LoginRequest request, StreamObserver<LoginResponse> responseObserver) {

        LoginResponse response = null;

        try {
            //1.根据用户编号查找获取用户对象信息（做校验判断，如果用户不存在抛出异常）
            TradeUser tradeUser = stockUserDao.getByUserNo(request.getUserNo());
            if(null == tradeUser){
                response = LoginResponse.newBuilder().setStatus(GlobalConstants.STATUS_ERROR)
                        .setMessage("用户不存在").build();
            }else {
                //2.用户密码校验，通过加密方式判断
                String encryptPwd = EncryptUtil.encryptSigned(request.getUserPwd());
                boolean pwdMatch = tradeUser.getUserPwd().equals(encryptPwd);
                if(!pwdMatch){
                    response = LoginResponse.newBuilder().setStatus(GlobalConstants.STATUS_ERROR)
                            .setMessage("密码错误！，请重新输入").build();
                }else {
                    //3.返回用户的登录成功信息（用户账号信息）
                    TradeAccount tradeAccount = tradeAccountDao.getByUserId(tradeUser.getId());

                    //4.更新用户登录的相关信息
                    stockUserDao.updateUserLogin(tradeUser.getId(), new Date());

                    response = LoginResponse.newBuilder().setStatus(GlobalConstants.STATUS_OK)
                            .setUserId(tradeUser.getId())
                            .setAccountId(tradeAccount.getId())
                            .setMessage("登录成功").build();
                    log.info("用户${}登录成功：", tradeUser.getName());
                }
            }
        }catch (Exception e){
            log.error(e.getMessage(),e);
            response = LoginResponse.newBuilder().setStatus(GlobalConstants.STATUS_ERROR)
                    .setMessage(e.getMessage()).build();
        }
        responseObserver.onNext(response);
        responseObserver.onCompleted();

    }

    /**
     * <pre>
     * 账户预警设置
     * </pre>
     */
    @Override
    public void accountWarnSetting(AccountWarnSettingRequest request,
                                   StreamObserver<AccountWarnSettingResponse> responseObserver) {


        log.info("Process in GrpcStockUserService.accountWarnSetting, request: " + request);
        AccountWarnSettingResponse reponse = null;

        try {
            // 设置账户预警信息
            tradeUserService.saveAccountWarnSetting(request);
            reponse = AccountWarnSettingResponse.newBuilder().setStatus(GlobalConstants.STATUS_OK).build();
        }catch(ComponentException e) {
            // 业务异常返回
            log.error(e.getMessage(), e);
            reponse = AccountWarnSettingResponse.newBuilder().setStatus(e.getErrorCodeEnum().getCode()).setMessage(e.getErrorCodeEnum().getMessage()).build();
        }catch(Exception e) {
            // 系统异常信息返回
            log.error(e.getMessage(), e);
            reponse = AccountWarnSettingResponse.newBuilder().setStatus(GlobalConstants.STATUS_ERROR).setMessage(e.getMessage() == null ? "null":e.getMessage()).build();
        }

        responseObserver.onNext(reponse);
        responseObserver.onCompleted();

    }
}
